<template>
  <span class="text-span" @dblclick="doOpen" v-show="!isShow">
    {{ getResult }} </span>
  <a-select @keydown.prevent.enter="isMultiple ? '' : confirm" v-show="isShow" v-model:value="value" allowClear
    @blur="confirm" @change="isMultiple ? '' : confirm" :placeholder="props.placeholder" show-search
    :filter-option="filterOptionMethod" style="width: 100%" :options="option" :mode="props.mode" />
</template>

<script setup lang='ts'>
import { watch, ref, computed } from "vue";
const props = defineProps(['options', 'mode', 'value', 'placeholder']);
const option = ref<any>([])
const emit = defineEmits(['confirm', 'open'])
const isShow = ref<boolean>(false);
const filterOptionMethod = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

const getResult = computed(() => {
  if (!props.value) return "--";
  if (isMultiple.value) {
    return props.value?.join('、') || "--"
  }
  return props.value
})

const isMultiple = computed(() => {
  return props.mode === 'multiple'
})
const value = ref<string | string[]>("");
watch(() => props.value, (val) => {
  if (!val) {
    value.value = !isMultiple.value ? "" : []
    return
  }
  value.value = JSON.parse(JSON.stringify(val));

}, { immediate: true })
watch(() => props.options, (val) => {
  if (isMultiple.value) {
    let list = JSON.parse(JSON.stringify(val));
    list.forEach(el => {
      el.value = el.label;
    });
    option.value = list
  } else {
    option.value = props.options
  }
}, { immediate: true })
const confirm = () => {
  isShow.value = false
  emit('confirm', value.value)
}
const doOpen = () => {
  isShow.value = true;
  emit('open', value.value);
}

</script>

<style lang="less" scoped>
.text-span {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: inline-block;
  flex: 1;
}
</style>